<template>
  <div>
    <div class="form-label">
      <span class="required">*</span>{{ caption }}
    </div>
    <van-uploader v-model="fileList" :max-count="8" upload-text="上传图片"
                  :max-size="maxSize" :before-delete="doDelFile"
                  :after-read="doUpload" :before-read="uploadCheck" @oversize="overSize"/>
  </div>
</template>

<script>
import {ajaxUtils, eraqConstants} from "@/utils/lwUtils";
import {apiUploadFile, apiListFile, apiDeleteFile} from "@/api/upload";

export default {
  name: "uploadFile",
  data() {
    return {
      fileList: [],
      maxSize: eraqConstants.FILE.maxSize * 1024 * 1024,
    }
  },
  props: ["unid", "fileType", "caption", "fn"],
  mounted() {
    //若fn为patch，先加载已上传的文件
    if (this.fn === "patch") {
      this.loadList(this.unid, this.fileType);
    }
  },
  methods: {
    doUpload: function (file) {
      let formData = new FormData();
      formData.append("unid", this.unid);
      formData.append("fileType", this.fileType);
      formData.append("file", file.file);
      apiUploadFile(formData).then(res => {
        if (ajaxUtils.checkFail(res.code, res.msg)) {
          return;
        }
        let idx = this.fileList.length - 1;
        this.fileList[idx].url = res.data.filePathOs;
        this.fileList[idx].unid = res.data.unid;
      }).catch(() => {
      });
    },
    loadList: function (unid, fileType) {
      this.fileList = [];

      apiListFile(unid, fileType).then(res => {
        res.data.forEach(attr => {
          this.fileList.push({
            unid: attr.unid, url: attr.filePathOs, file: new File([], attr.fileName, {})
          });
        });
      }).catch(err => {
        ajaxUtils.showErr(err);
      });
    },
    doDelFile: function (file) {
      let unid = file.unid;
      console.log(unid);
      apiDeleteFile(unid, "").then(res => {
        for (let i = 0, n = this.fileList.length; i < n; i++) {
          if (this.fileList[i].unid !== unid) {
            continue;
          }
          this.fileList.splice(i, 1);
        }
        this.$eraqDlg.info(res.msg);
      }).catch(() => {
      });
    },
    uploadCheck: function (file) {
      if (!eraqConstants.FILE.exts.includes(file.type)) {
        this.$eraqDlg.warning('只允许上传【' + eraqConstants.FILE.extNames + '】格式的图片文件');
        return false;
      }
      return true;
    },
    overSize: function () {
      this.$eraqDlg.warning('文件超过限制大小【' + eraqConstants.FILE.maxSize + 'MB】');
    }
  }
}
</script>

<style lang='scss' scoped>
@import "src/css/home";
</style>
